package com.utrailer.wlt.gateway.filter;

import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpMethod;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 *
 * @author Chen Song
 * @since
 * @see RequestLogGlobalFilter
 */
@Deprecated
@Log4j2
public class RequestLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (exchange.getRequest().getMethod() == HttpMethod.POST) {
            Flux<DataBuffer> body = exchange.getRequest().getBody();
            body.subscribe(buffer -> {
                byte[] bytes = new byte[buffer.readableByteCount()];
                buffer.read(bytes);
                String bodyString = new String(bytes, StandardCharsets.UTF_8);
                log.info("Request path[{}], Request Param[{}]", exchange.getRequest().getPath(), bodyString);
            });
        } else {
            MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
            log.info("Request path[{}], Request Param[{}]", exchange.getRequest().getPath(), queryParams);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
